#include "smart-device-net-protocol.h"

void SmartDeviceNetProtocol::addOperation(const string &operation)
{
    root["operation"] = operation;
}

void SmartDeviceNetProtocol::addCommand(const string &command)
{
    root["command"] = command;
}

void SmartDeviceNetProtocol::addDeviceType(const string &type)
{
    root["device"]["deviceType"] = type;
}

void SmartDeviceNetProtocol::addDeivceNumber(const string &number)
{
    root["device"]["deviceNumber"] = number;
}

void SmartDeviceNetProtocol::addDevice(const string &type, const string &number)
{
    addDeviceType(type);
    addDeivceNumber(number);
}

void SmartDeviceNetProtocol::addResult(const string &errmsg, const string &data)
{
    root["result"]["errmsg"] = errmsg;
    root["result"]["data"] = data;
}

void SmartDeviceNetProtocol::addListItem(const string &operation, const string &type, const string &number)
{
    Json::Value item;
    item["operation"] = operation;
    item["deviceType"] = type;
    item["deviceNumber"] = number;
    objArray.append(item);
}

void SmartDeviceNetProtocol::addListResult(const string &errmsg)
{
    root["result"]["errmsg"] = errmsg;
    root["result"]["devices"] = objArray;
}

string SmartDeviceNetProtocol::toString()
{
    return root.toStyledString();
}

string SmartDeviceNetProtocol::getOperation(void) const
{
    return root["operation"].asString();
}

string SmartDeviceNetProtocol::getCommand(void) const
{
    return root["command"].asString();
}

string SmartDeviceNetProtocol::getDeviceValue(const string &key)
{
    return root["device"][key].asString();
}

uint32_t SmartDeviceNetProtocol::getDeviceType(void) const
{
    string type = root["device"]["deviceType"].asString();
    return stoi(type, 0, 16);
}

uint32_t SmartDeviceNetProtocol::getDeviceNumber(void) const
{
    string number = root["device"]["deviceNumber"].asString();
    return stoi(number, 0, 16);
}

uint32_t SmartDeviceNetProtocol::getUserID(void)
{
    string number = root["userid"].asString();
    return stoi(number, 0, 16);
}

bool SmartDeviceNetProtocol::empty(void) const
{
    return root.empty();
}

SmartDeviceNetProtocol SmartDeviceNetProtocol::fromJsonData(const string &jsonData)
{

    SmartDeviceNetProtocol protocol;
    Json::Reader reader;
    bool ok = reader.parse(jsonData, protocol.root);
    if (!ok)
    {

        fprintf(stderr, "Fail to reader.parse\n");
    }

    return protocol;
}